package ioc

import (
	"errors"
	"gitee.com/xiao_hange/go-admin-log/log/ioc/config"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"gopkg.in/yaml.v2"
)

// func InitNacos() config_client.IConfigClient {
func InitNacos(serverName string) *config.AppConfig {

	type Config struct {
		IP          string `yaml:"ip"`
		Port        uint64 `yaml:"port"`
		NamespaceID string `yaml:"namespaceId"`
	}
	var cfg Config
	err := viper.UnmarshalKey("nacos", &cfg)
	if serverName == "" {
		panic(errors.New("请输入服务名称"))
	}
	cs := []constant.ServerConfig{
		{
			IpAddr: cfg.IP,
			Port:   cfg.Port,
		},
	}
	cc := constant.ClientConfig{
		NamespaceId:         cfg.NamespaceID,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		CacheDir:            "tmp/nacos/cache/",
		//LogDir:              "tmp/nacos/log",
		//LogLevel:            "debug",
	}
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": cs,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: serverName,
		Group:  "dev", // TODO 可以改成启动输入的形式
	})
	if err != nil {
		panic(err)
	}
	appConfig := config.AppConfig{}
	err = yaml.Unmarshal([]byte(content), &appConfig)
	return &appConfig
}
